// src/Dep.js
let dId = 0

export class Dep {
  constructor() {
    // 每个dep的id都是独一无二的
    this.id = dId++
    // 用来存储Watcher的数组
    this.subs = []
  }

  depend() {
    if (Dep.target) {
      // 此时Dep.target指向的是某个Wacther，Wacther也要把此dep给收集起来
      Dep.target.addDep(this)
    }
  }

  notify() {
    // 通知subs里的每个Wacther都去通知更新
    const tempSubs = this.subs.slice()
    tempSubs.reverse().forEach((watcher) => watcher.update())
  }

  addSub(watcher) {
    // 将Watcher收进subs里
    this.subs.push(watcher)
  }
}

let stack = []
export function pushTarget(watcher) {
  // 改变target的指向
  Dep.target = watcher
  stack.push(watcher)
}

export function popTarget() {
  stack.pop()
  Dep.target = stack[stack.length - 1]
}
